import React, { useState, useEffect } from 'react';
import { Modal, Form, Select, notification } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import { editStudents, studentsList, parentsList } from '@/services/api';
import { SIZE, PAGE, ALL } from '@/utils/constant';

interface props {
  onClose: () => void;
  dispatch: any;
}

interface UserFormProps extends FormComponentProps {
  ref: any;
  parent: object;
}

const ref: any = React.createRef();
const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(({ form: { getFieldDecorator }, parent }: any) => {
  const [parentsData, setParentsData] = useState([parent]);
  const { id } = parent;

  const formItemLayout = {
    labelCol: {
      xs: { span: 4, offset: 4 },
    },
    wrapperCol: {
      sm: { span: 8 },
    },
  };

  useEffect(() => {
    if (!id) {
      parentsList({ page: PAGE, size: SIZE }).then((resp: any) => {
        if (resp.status === 'success') {
          setParentsData(resp.data.data);
        }
      });
    }
  }, []);

  return (
    <Form layout="horizontal" {...formItemLayout}>
      <Item label="家长">
        {getFieldDecorator('parent_id', {
          initialValue: id,
          rules: [
            {
              required: true,
              message: '必填',
            },
          ],
        })(
          <Select
            placeholder="请选择"
            allowClear
            showSearch
            defaultActiveFirstOption={false}
            filterOption={false}
            onSearch={value => {
              if (value) {
                const searchValue = value.trim();
                parentsList({ page: PAGE, size: ALL, keyword: searchValue }).then((resp: any) => {
                  if (resp.status === 'success') {
                    setParentsData(resp.data.data);
                  }
                });
              }
            }}
          >
            {parentsData.map((item: any) => {
              if (item.id) {
                return (
                  <Select.Option value={item.id} key={item.id}>
                    {item.name}
                  </Select.Option>
                );
              }
              return;
            })}
          </Select>,
        )}
      </Item>
    </Form>
  );
});

const UpdateParent = ({ onClose, dispatch }: props) => {
  const studentsData = JSON.parse(sessionStorage.getItem('studentsData') || '');
  let { parent } = studentsData;
  if (!parent) {
    parent = {};
  }
  return (
    <Modal
      visible
      onCancel={onClose}
      maskClosable={false}
      title="更改(绑定)家长"
      onOk={() => {
        ref.current.validateFields({ first: true }, (err: any, val: any) => {
          if (!err) {
            const parent_id = val.parent_id || '';
            const newVal: any = {
              parent_id,
            };

            const residence_images: any = [];
            const health_images: any = [];
            studentsData.residences.forEach((item: any) => {
              residence_images.push(item.id);
            });
            studentsData.healths.forEach((item: any) => {
              health_images.push(item.id);
            });
            newVal.residence_images = residence_images;
            newVal.health_images = health_images;
            delete studentsData.parent;
            delete studentsData.teacher;
            delete studentsData.clase;
            delete studentsData.image;
            delete studentsData.residences;
            delete studentsData.healths;

            editStudents({ ...studentsData, ...newVal }).then((resp: any) => {
              if (resp.status === 'success') {
                notification.success({ message: '修改家长成功' });
                onClose();
                dispatch({
                  type: 'OPEN_LOADING',
                });
                studentsList({ page: PAGE, size: SIZE })
                  .then((res: any) => {
                    if (res.status === 'success') {
                      dispatch({
                        type: 'GET_DATA',
                        payload: res.data.data,
                      });
                      dispatch({
                        type: 'CHANGE_PAGINATION',
                        payload: {
                          current: PAGE,
                          pageSize: SIZE,
                          total: res.data.meta.total,
                        },
                      });
                    }
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  })
                  .catch(() => {
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  });
              }
            });
          }
        });
      }}
    >
      <MyForm ref={ref} parent={parent} />
    </Modal>
  );
};

export default UpdateParent;
